package controller

import (
	"fmt"
	"log"
	"mumu_stock_trad/model"
	"mumu_stock_trad/util"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

func GetHistory(code string, name string) {
	// 获取当前时间
	now := time.Now()
	todayYear := now.Year()

	log.Printf(fmt.Sprintf("开始运行股票：%dcode:%s", name, code))

	// 循环两年的月份
	for year := todayYear; year <= todayYear; year++ {
		for month := 1; month <= 9; month++ {
			// 创建当月第一天的时间对象
			begin := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.Local)

			// 获取当月最后一天
			end := begin.AddDate(0, 1, -1).Format("2006-01-02")
			// 调用 Util 中的函数获取股票数据
			list, _, err := util.FetchStockListSApi(code, name, begin.Format("2006-01-02"), end)
			if err != nil {
				log.Printf("Error fetching stock data: %v", err)
			}
			for _, st := range list {
				dad := st
				dad.SaveStockSApi()
			}
		}
	}
}

// GetStockData 获取股票数据的控制器
func StockSApi(c *gin.Context) {
	page := 1
	pageSize := 20000
	stocks, err := model.GetStockListPage(page, pageSize)
	if err != nil {
		log.Printf("Error saving stock data: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save stock data"})
		return
	}

	// list := []model.StockDataShowApi{}

	i := 1
	for k, da := range stocks {
		time.Sleep(time.Millisecond * 3)
		i++
		// c.JSON(http.StatusOK, gin.H{
		// 	"message": fmt.Sprintf("开始运行%s股票：%dcode:%s", k, da.Name, da.Code),
		// })

		log.Printf(fmt.Sprintf("开始运行%s股票：%dcode:%s", k, da.Name, da.Code))

		// 获取当前时间
		now := time.Now()
		todayYear := now.Year()

		// 循环两年的月份
		for year := todayYear; year <= todayYear; year++ {
			for month := 1; month <= 9; month++ {
				// 创建当月第一天的时间对象
				begin := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.Local)

				log.Printf(fmt.Sprintf("开始运行%s股票：%dcode:%s", k, da.Name, begin))
				// 获取当月最后一天
				end := begin.AddDate(0, 1, -1).Format("2006-01-02")
				code := da.Code
				// 调用 Util 中的函数获取股票数据
				list, _, err := util.FetchStockListSApi(code, da.Name, begin.Format("2006-01-02"), end)
				if err != nil {
					log.Printf("Error fetching stock data: %v", err)
					c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch stock data"})
					return
				}
				for _, st := range list {
					dad := st
					dad.SaveStockSApi()
				}
			}
		}

		// model.BatchInsert(list)
		if i > 300 {
			i = 0
			time.Sleep(time.Second * 1)
		}
	}

	// 返回成功响应
	c.JSON(http.StatusOK, gin.H{
		"message": "Stock data saved successfully",
	})
}
